package com.cshuig.hadoop.sort;

import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * Created by hogan on 2015/10/30.
 * 因为要实现排序, 所以要实现
 */
public class InforBean implements WritableComparable<InforBean> {

    private String account;
    private double income;
    private double expense;
    private double surplus;

    public void set(String account, double income, double expense) {
        this.account = account;
        this.income = income;
        this.expense = expense;
        this.surplus = income - expense;
    }
    /**
     * 排序规则
     * 收入大的排前面, 如果收入一样, 那么支出小的排前面
     * mapper中的key2类型， 就是此方法的参数类型, 只要mapper将这个类型作为k2输出, 那么就会自动排序(即调用这个方法)
     * @param inforBean
     * @return
     */
    public int compareTo(InforBean inforBean) {
        if (this.income == inforBean.getIncome()) {
            return this.expense > inforBean.getExpense() ? -1 : 1;
        } else {
            return this.income > inforBean.getIncome() ? 1 : -1;
        }
    }

    public void write(DataOutput out) throws IOException {
        out.writeUTF(account);
        out.writeDouble(income);
        out.writeDouble(expense);
        out.writeDouble(surplus);
    }

    public void readFields(DataInput in) throws IOException {
        this.account = in.readUTF();
        this.income = in.readDouble();
        this.expense = in.readDouble();
        this.surplus = in.readDouble();
    }


    @Override
    public String toString() {
        return income + "\t" + expense + "\t" + surplus;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public double getIncome() {
        return income;
    }

    public void setIncome(double income) {
        this.income = income;
    }

    public double getExpense() {
        return expense;
    }

    public void setExpense(double expense) {
        this.expense = expense;
    }

    public double getSurplus() {
        return surplus;
    }

    public void setSurplus(double surplus) {
        this.surplus = surplus;
    }
}
